class HEMiDEMi
require 'open-uri'
require 'rubygems'
require 'hpricot'
=begin
Format:
  rss/bookmark/[recent|popular|recommendation|recent_recommendation|recent_popular].xml
  rss/user/xxx/bookmark/[recent|recommendation].xml
  rss/group/xxx/bookmark/[recent|popular|recommendation|recent_recommendation|recent_popular].xml
  rss/bookmark/tag/[tagname].xml
  rss/user/xxx/bookmark/tag/[tagname].xml
  rss/group/xxx/bookmark/tag/[tagname].xml
=end
  HEMiDEMi_URL = "http://www.hemidemi.com/"
  BOOKMARKS_URL = HEMiDEMi_URL + "rss/bookmark/"
  USER_BOOKMARKS_URL = HEMiDEMi_URL + "rss/user/"
  GROUP_BOOKMARKS_URL = HEMiDEMi_URL + "rss/group/"
  def method_missing(m_id, options=nil, *args)
    # options => Hash
    # {:user => "garylin", :group => "ruby_and_ror", :tag => "tag"}
    bkms = $1 if m_id.to_s =~ /^get_(\w+)_bookmarks/
    ubkms = $1 if m_id.to_s =~ /^get_(\w+)_bookmarks_by_user/
    gbkms = $1 if m_id.to_s =~ /^get_(\w+)_bookmarks_by_group/
    tags = $1 if m_id.to_s =~ /^get_tag_bookmarks_by_(\w+)/
    from, type = $1, $2 if m_id.to_s =~ /^get_url_by_(\w+)_(\w+)/
    type = $1 if m_id.to_s =~ /^get_url_by_(\w+)/
    
    super(m_id) if (bkms.nil? && ubkms.nil? && gbkms.nil? && tags.nil? && type.nil?)
    # Get Bookmarks in recent or others
    @url = BOOKMARKS_URL + bkms.to_s + ".xml" unless (bkms.nil? || bkms.size < 1)
    
    # Get Bookmarks in recent or recommend by user
    @url = USER_BOOKMARKS_URL + options.to_s + "/bookmark/" + ubkms.to_s + ".xml" if (options.is_a?(String) && (!ubkms.nil? || (ubkms.size > 0) if ubkms.is_a?(String)))

    # Get bookmarks in recent of others by group
    @url = GROUP_BOOKMARKS_URL + options.to_s + "/bookmark/" + gbkms.to_s + ".xml" if (options.is_a?(String) && (!gbkms.nil? || (gbkms.size > 0) if gbkms.is_a?(String)))
    
    # Get bookmarks by tag
    # @url = tags.to_s + user + "/bookmark/tag/" + tag + ".xml"
    case tags
      when "user"
        user, tag = options[:user], options[:tag] if options.is_a?(Hash)
        @url = USER_BOOKMARKS_URL + user + "/bookmark/tag/" + tag + ".xml"
      when "group"
        group, tag = options[:group], options[:tag] if options.is_a?(Hash)
        @url = GROUP_BOOKMARKS_URL + group + "/bookmark/tag/" + tag + ".xml"
    end

    return self.send("get_#{type.to_s.split("_")[1]}_bookmarks_by_#{from}", options) if (!from.nil? && !type.nil?)
    return self.send("get_#{type}_bookmarks") unless type.nil?
    return @url if !@url.nil?
  end
  
  def get_rss(from="", name="", type="recent")
    doc = nil
    if (from.size > 0 && name.size > 0)
      doc = Hpricot(open(self.send("get_url_by_#{from}_#{type}", name)))
    else
      doc = Hpricot(open(self.send("get_url_by_#{type}")))
    end
    search = doc.search("//channel/item")
    return [search, search.size]
  end
  
end